// pages/account/account.js
import {
  UserModel
} from '../../models/user.js';

import {
  ContentModel
} from '../../models/content.js';

import {
  config
} from '../../utils/config';

import {
  enums
} from '../../utils/enums';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const util = require('../../utils/util.js');

const user = new UserModel();

const content = new ContentModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
      tabName: "历史记录",
      key: "1"
    }, {
      tabName: "我的收藏",
      key: "2"
    }],
    modify: false,
    userId: 0,
    user: {},
    defaultBg: "../../images/static/bg.jpeg",
    loadingHidden: true,
    historyPageIndex: 1,
    history: [],
    historyTotal: 0,
    collectPageIndex: 1,
    collect: [],
    collectTotal: 0,
    activeKey: "1",
    historyLoading: {
      "show": false,
      "type": "loading"
    },
    collectLoading: {
      "show": false,
      "type": "loading"
    },
    slideDelTip: false,
    slideCancelCollectTip: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
    });
  },

  _loadData() {
    user.getUserInfo().then(res => {
      let user = res.data;
      user.fansNum = !user.fansNum ? 0 : user.fansNum;
      user.followedNum = !user.followedNum ? 0 : user.followedNum;
      user.wonLikedNum = !user.wonLikedNum ? 0 : user.wonLikedNum;
      this.setData({
        user: res.data
      })
    })
  },

  /**
   * 加载我的浏览记录
   */
  _loadHistory() {
    content.myHistory(this.data.historyPageIndex).then(res => {

      this.setData({
        historyTotal: res.data.total
      })

      if (res.data.content.length > 0) {

        res.data.content.forEach(e => {
          e.viewTime = util.timeSpan(e.viewTime);
          // 设置删除按钮
          e.slided = false;
        });

        //数组合并
        this.data.history.push.apply(this.data.history, res.data.content);
        this.setData({
          history: this.data.history
        });
      }

      /**
       * 页面操作指示
       */
      let slideDelTip = wx.getStorageSync(enums.slideDelTip);
      if (!slideDelTip) {
        if (this.data.history.length > 0) {
          this.data.history[0].tip = true;
          this.setData({
            history: this.data.history
          })

          // 3秒之后关闭提示
          setTimeout(() => {
            wx.setStorageSync(enums.slideDelTip, !slideDelTip);
            this.data.history[0].tip = false;
            this.setData({
              history: this.data.history
            })
          }, 3000);
        }
      }
    });
  },

  /**
   * 加载我的收藏
   */
  _loadMyCollect() {
    content.myCollect(this.data.collectPageIndex).then(res => {

      wx.hideLoading();
      this._closeSkeletonView();

      this.setData({
        collectTotal: res.data.total
      })

      if (res.data.content.length > 0) {

        // 设置删除按钮
        res.data.content.forEach(e => {
          e.slided = false;
        });

        //数组合并
        this.data.collect.push.apply(this.data.collect, res.data.content);
        this.setData({
          collect: this.data.collect
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    token.verify().then(res => {
      if (res) {
        that._init();
        that._loadData();
        that._loadHistory();
        that._loadMyCollect();
      }
    });
  },

  _init() {
    this.setData({
      historyPageIndex: 1,
      history: [],
      historyTotal: 0,
      collectPageIndex: 1,
      collect: [],
      collectTotal: 0,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this._closeModifyView();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.activeKey === '1') {
      if (this.data.historyTotal == this.data.history.length) {
        // 加载全部
        this._showHistoryLoadedAllTip();
      } else {
        this.data.historyPageIndex++;
        this._showHistoryLoadMoreTip();
        this._loadHistory();
      }
    } else {
      if (this.data.collectTotal == this.data.collect.length) {
        // 加载全部
        this._showCollectLoadedAllTip();
      } else {
        this.data.collectPageIndex++;
        this._showCollectLoadMoreTip();
        this._loadMyCollect();
      }
    }
  },
  onPopup() {
    this._closeModifyView();
  },
  onSetting() {
    this._openModifyView();
  },
  onModify() {
    wx.navigateTo({
      url: `../modify/modify?userId=${this.data.user.id}`,
    })
  },
  _openModifyView() {
    this.setData({
      modify: true
    })
  },
  _closeModifyView() {
    this.setData({
      modify: false
    })
  },
  onChangeBg() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // 附带文件上传
        user.modifyWithFile(config.baseUrl, res.tempFilePaths[0], that.data.user, 'covered').then(res => {
          if (!res.data.result) {
            that._show_tip(res.data.msg);
          } else {
            that._show_tip('修改成功');
            setTimeout(() => {
              that._closeModifyView();
              that._loadData()
            }, 900);
          }
        });
      }
    })
  },
  _show_tip(msg = '修改背景图片失败') {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
  },
  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  onRelation() {
    wx.navigateTo({
      url: '../my-list/my-list',
    })
  },
  changeTabs(e) {
    let activeKey = e.detail.activeKey;
    this.setData({
      activeKey: activeKey
    })

    if (activeKey === '2') {
      /**
       * 页面操作指示
       */
      let slideCancelCollectTip = wx.getStorageSync(enums.slideCancelCollectTip);
      if (!slideCancelCollectTip) {
        if (this.data.collect.length > 0) {
          this.data.collect[0].tip = true;
          this.data.collect[0].tipMsg = "取消收藏";
          this.setData({
            collect: this.data.collect
          })

          // 3秒之后关闭提示
          setTimeout(() => {
            wx.setStorageSync(enums.slideCancelCollectTip, !slideCancelCollectTip);
            this.data.collect[0].tip = false;
            this.setData({
              collect: this.data.collect
            })
          }, 3000);
        }
      }
    }
  },
  _showHistoryLoadedAllTip() {
    this.setData({
      historyLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeHistoryLoadedAllTip() {
    this.setData({
      historyLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showHistoryLoadMoreTip() {
    this.setData({
      historyLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeHistoryLoadMoreTip() {
    this.setData({
      historyLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },
  _showCollectLoadedAllTip() {
    this.setData({
      collectLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeCollectLoadedAllTip() {
    this.setData({
      collectLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showCollectLoadMoreTip() {
    this.setData({
      collectLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeCollectLoadMoreTip() {
    this.setData({
      collectLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },
  toDetail(e) {
    let params = e.detail;

    // 跳转到详情页
    wx.navigateTo({
      url: `../detail/detail?id=${params.id}`,
    });
  },
  onSlideHistoryOpen(e) {

    let id = e.currentTarget.dataset.id;

    this.data.history.forEach(e => {
      if (id === e.id) {
        e.slided = false
      } else {
        e.slided = true
      }
    })

    this.setData({
      history: this.data.history
    })
  },
  onSlideCollectOpen(e) {

    let id = e.currentTarget.dataset.id;

    this.data.collect.forEach(e => {
      if (id === e.id) {
        e.slided = false
      } else {
        e.slided = true
      }
    })

    this.setData({
      collect: this.data.collect
    })
  },
  onDelHistory(e) {
    let that = this;
    let contentId = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;

    wx.showModal({
      title: '提示',
      content: '确定要删除历史记录吗？',
      success: function (sm) {
        if (sm.confirm) {
          user.delViewHistory(contentId).then(res => {
            that.data.history.splice(index, 1);
            that.setData({
              history: that.data.history,
              historyTotal: that.data.historyTotal - 1
            })
          });
        } else if (sm.cancel) {
          that.data.history[index].slided = true;
          that.setData({
            history: that.data.history,
          })
        }
      }
    })
  },
  onCancelCollect(e) {
    let that = this;
    let contentId = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;

    wx.showModal({
      title: '提示',
      content: '确定要取消收藏吗？',
      success: function (sm) {
        if (sm.confirm) {
          user.cancelMyCollect(contentId).then(res => {
            that.data.collect.splice(index, 1);
            that.setData({
              collect: that.data.collect,
              collectTotal: that.data.collectTotal - 1
            })
          });
        } else if (sm.cancel) {
          that.data.collect[index].slided = true;
          that.setData({
            collect: that.data.collect,
          })
        }
      }
    })
  }
})